package com.sf.marathon.soul.service;

import com.sf.marathon.soul.Common;
import com.sf.marathon.soul.domain.ExpressGroup;
import com.sf.marathon.soul.dao.ExpressGroupMapper;
import com.sf.marathon.soul.domain.ProMarketBase;
import com.sf.marathon.soul.service.ExpressGroupService;
import com.sf.marathon.soul.core.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 集货拼团表 服务实现类
 * </p>
 *
 * @author 325175
 * @since 2017-12-15
 */
@Service
public class ExpressGroupService extends BaseService<ExpressGroupMapper, ExpressGroup> {

    @Autowired
    private ProMarketBaseService proMarketBaseService;

    public List<ExpressGroup> findUnfinishGroupByUserId(Long userId){
        Map<String,Object> query = new HashMap<>();
        query.put("group_status",ExpressGroup.STATUS_ING);

        return super.baseDao.selectByMap(query);
    }

    /**
     * 自动生成集货团
     * @param data
     */
    public void generateGroup(ProMarketBase data) {
        ExpressGroup group = new ExpressGroup();
        group.setMaketId(data.getId());
        // 分钟
        Integer duration = data.getGroupDuration();
        long endTimeMillis = System.currentTimeMillis() + (duration * 1000 * 60);
        group.setBeginTime(new Date());
        Date endTime = new Date();
        endTime.setTime(endTimeMillis);
        group.setEndTime(endTime);
        group.setGroupStatus("0");
        StringBuilder sb = new StringBuilder(20);
        sb.append(data.getMaketName()).append(Common.getGroupNameSeq()).append("期");
        group.setGroupName(sb.toString());
        group.setLeftNum(data.getGroupLimit());
        insert(group);
    }

    public void finishGroup() {
        Map<String,Object> query = new HashMap<>();
        query.put("group_status",ExpressGroup.STATUS_ING);

        List<ExpressGroup> groups = super.baseDao.selectByMap(query);
        Date now = new Date();
        for(ExpressGroup g : groups){
            if(isOver(now,g.getEndTime())){
                g.setGroupStatus(ExpressGroup.STATUS_FAIL);
                super.baseDao.updateById(g);
                ProMarketBase m = (ProMarketBase) proMarketBaseService.selectById(g.getMaketId());
                generateGroup(m);
            }
        }
    }

    private boolean isOver(Date time,Date over){
        return over.before(time);
    }
}
